package com.self.smallma.myblogweb.web;

import com.self.smallma.myblogweb.entity.MessageEntity;
import com.self.smallma.myblogweb.entity.UserEntity;
import com.self.smallma.myblogweb.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 留言页面控制器
 */
@Controller
public class MessageShowController {
    @Autowired
    MessageService messageService;


    @Value("${message.avatar}")
    private String avatar;

    /**
     * @return
     */
    @GetMapping("/message")
    public String messages() {

        return "message";
    }


    //    查询留言
    @GetMapping("/messagecomment")
    public String find(Model model) {
        List<MessageEntity> messages = messageService.listMessage();
        model.addAttribute("messages", messages);
        return "message::messageList";
    }
    //    新增留言
    @PostMapping("/message")
    public String save(MessageEntity message, HttpSession session, Model model) {
        UserEntity user = (UserEntity) session.getAttribute("user");

        if (user !=null){
            if (user.getUserId()==1){
                //管理员
                message.setAvatar(user.getAvatar());
                message.setAdminMessage(1);
            }else {
                //普通用户
                message.setAvatar(user.getAvatar());
                message.setAdminMessage(0);
            }

        }else {
            //未登录
            //message.setAvatar(avatar);
            return "admin/register";

        }
        if (message.getParentMessage().getId() != null) {
            message.setParentMessageId(message.getParentMessage().getId());
        }
        messageService.saveHasTime(message);
       List<MessageEntity> messageEntities = messageService.listMessage();
        model.addAttribute("messages", messageEntities);
        return "message::messageList";
    }

    //    删除留言
    @GetMapping("/messages/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes, Model model){
        messageService.removeById(id);
        return "redirect:/message";
    }
}
